package eva.savant.core.secure

import eva.savant.core.view.Base
import eva.savant.business.administrador.service.QSAdministrador

import org.springframework.security.core.Authentication
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import javax.naming.Context
import javax.naming.directory.InitialDirContext
import javax.naming.NamingException

public class AuthenticationProvider implements org.springframework.security.authentication.AuthenticationProvider {

  static def AUTHORITIES = new ArrayList<GrantedAuthority>()

  static { AUTHORITIES.add new SimpleGrantedAuthority('ROLE_READER') }


  public Authentication authenticate(Authentication auth) {

    if(isUserSystem(auth.principal+'',auth.credentials+'',auth.details+''))

    return new UsernamePasswordAuthenticationToken(auth.name, auth.credentials, AUTHORITIES)


    throw new BadCredentialsException('El usuario o el password es incorrecto para ' + auth.principal)
  }

  public boolean supports(Class<?> authentication) {

    return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication))
  }

  private static boolean isUserSystem(String username, String password, String sociedad) {

    return Base.entityService.getEntity(QSAdministrador.isUser,username,password,sociedad) != null
  }

}